
/****** Object:  StoredProcedure [dbo].[ws_ins_voucher2]    Script Date: 10/19/2013 09:22:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'ws_ins_voucher2')
DROP PROCEDURE ws_ins_voucher2
GO

CREATE PROCEDURE [dbo].[ws_ins_voucher2] 
(		
	@terminal_id varchar(255), 
	@kortelesnr varchar(255), 
	@nuol_kort_nr varchar(255), 
	@apm_rusis varchar(255), 
	@znr varchar(255),
	@n_kvitonr varchar(255),
	@n_data varchar(255)
)
AS
BEGIN

	DECLARE @nuo datetime
	DECLARE @iki datetime
	DECLARE @galvaid int
	DECLARE @data datetime
	DECLARE @kvitonr int
	DECLARE @KvNr int
	DECLARE @tmp varchar(11)
	DECLARE @mok numeric(12,2)
	
	BEGIN TRANSACTION
	    SELECT top 1 @tmp = SUBSTRING(kvitonr2,1,CHARINDEX('/', kvitonr2)-1) from kvitogalva where aparatoid = @terminal_id and znr = @znr order by id desc
		
		
		if (@tmp is null)
			SET @KvNr = 1
		else
			SET @KvNr = CAST(@tmp as int) + 1
	    SET @data = convert(datetime,@n_data ,126)
		SET @kvitonr = (@znr*65536)+@KvNr
		
		insert into Kvitogalva  (aparatoid,kortelesnr,kvitonr,kvitonr2,data,import,year,month,day,hour,minute,znr,apmokejimorusis,nlkort,n_kvitonr) 
		values (cast(@terminal_id as int),case when @kortelesnr= 'NULL' then null else @kortelesnr end,@kvitonr ,cast(@KvNr as varchar(10))+'/'+cast(@znr as varchar(10)),@data,0,year(@data),month(@data),day(@data), DATEPART(hh, @data),DATEPART(mi,@data),@znr,@apm_rusis,case when @nuol_kort_nr= 'NULL' then null else @nuol_kort_nr end,@n_kvitonr )
		
		SET @galvaid  = SCOPE_IDENTITY()

		DECLARE @barkodas varchar(100)
		DECLARE @kiekis varchar(100)
		DECLARE @kaina varchar(100)
		DECLARE @mokesciai varchar(100)
		DECLARE @suma decimal(12,2)
	    DECLARE @nuol_suma decimal(12,2)
		DECLARE @nuol varchar(100)
		
		DECLARE MY_CURSOR CURSOR 
		  LOCAL STATIC READ_ONLY FORWARD_ONLY
		FOR 
		SELECT barkodas,kiekis,kaina,mokesciai,nuol_suma
		FROM #tt_eilutes
		
		OPEN MY_CURSOR
		FETCH NEXT FROM MY_CURSOR INTO @barkodas,@kiekis,@kaina,@mokesciai,@nuol
		WHILE @@FETCH_STATUS = 0
		BEGIN 

		SET @suma = cast(isnull(@kaina,0) as decimal(12,2))/cast(isnull(@kiekis,1) as decimal(12,2))
		SET @mok = cast(@mokesciai as numeric(10,2)) 
		SET @nuol_suma = cast(@nuol as numeric(10,2)) 

		insert into Kvitoeilute (barkodas,preke,kiekis,kaina,mokesciai,galvosid,suma,nuolaida ) 
		values (@barkodas,@barkodas,@kiekis,@suma,@mok,@galvaid,cast(isnull(@kaina,0) as decimal(12,2)),@nuol_suma)

		FETCH NEXT FROM MY_CURSOR INTO @barkodas,@kiekis,@kaina,@mokesciai,@nuol
		END
		CLOSE MY_CURSOR
		DEALLOCATE MY_CURSOR

		update Kvitogalva set 
		suma=(select sum(suma) from Kvitoeilute where galvosid=@galvaid),
		mokesciai=(select sum(mokesciai) from Kvitoeilute where galvosid=@galvaid) where id = @galvaid
		
		
	COMMIT TRANSACTION

END

GO

